//
//  ECSZipArchive.m
//  ECS DevelopKit
//
//  Created by LittoCats on 8/27/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "ECSArchiver.h"
#import "ZipArchive.h"

@implementation ECSArchiver

+ (void)uncompressFile:(NSString *)file to:(NSString *)path completionHanlder:(void (^)(NSError *error))completionHanlder
{
    NSString *sourceFile = [file hasPrefix:@"/"] ? file : [[NSHomeDirectory() stringByAppendingPathComponent:file] stringByResolvingSymlinksInPath];
    NSString *destinationPath = [path hasPrefix:@"/"] ? path : [[NSHomeDirectory() stringByAppendingPathComponent:path] stringByResolvingSymlinksInPath];
    NSString *fileType = [file pathExtension];
    if ([fileType isEqualToString:@"zip"]) {
        [self unzipFile:sourceFile to:destinationPath completionHanlder:^(NSError *error) {
            if (completionHanlder) {
                completionHanlder(error);
            }
        }];
    }
    
}

+ (void)unzipFile:(NSString *)file to:(NSString *)path completionHanlder:(void (^)(NSError *error))completionHanlder
{
    ZipArchive* zipArchive = [[ZipArchive alloc] init];
    if (![zipArchive UnzipOpenFile:file]) {
        completionHanlder([NSError errorWithDomain:@"[ECSZipArchive] unzip" code:90001 userInfo:@{@"errorDes":@"file can't be opened ."}]);
    }else{
        BOOL ret = [zipArchive UnzipFileTo:path overWrite: YES];
        if (YES != ret) {
            completionHanlder([NSError errorWithDomain:@"[ECSZipArchive] unzip" code:90001 userInfo:@{@"errorDes":@"file can't be uncompressed by zip ."}]);
        }else{
            [zipArchive UnzipCloseFile];
            completionHanlder(nil);
        }
    }
}
@end
